package com.itheima.edu.info.manager.service;

import com.itheima.edu.info.manager.dao.TeacherDao;
import com.itheima.edu.info.manager.domain.Teacher;

/**
 * @Author 王加鑫
 * @Date 2021/5/4 20:41
 * @Version 1.0
 */
public class TeacherService {
    private TeacherDao teacherDao = new TeacherDao();

    /*
    添加老师
     */
    public boolean addTeacher(Teacher teacher) {
        return teacherDao.addTeacher(teacher);
    }

    /*
    校验tId是否重复
     */
    public int isExists(String tId) {
        //标记位思想:默认认为数组没有重复sId,flag为false
        int index = -1;
        //指挥dao层查出来所有的数据再进行判断
        Teacher[] teachers = teacherDao.findAllTeacher();
        for (int i = 0; i < teachers.length; i++) {
            //当数组元素不为空且取出来的值等于传过来的sId值时,说明id重复
            if(teachers[i] != null && teachers[i].getId().equals(tId)){
                index = i;
            }
        }
        return index;
    }

    /*
    查询全部老师数据
     */
    public Teacher[] findAllTeacher() {
        //指挥dao层查询数据
        Teacher[] teachers = teacherDao.findAllTeacher();
        //标记位思想：假设数组全部为空
        boolean flag = false;
        //只有当数组有元素不为null时才将查询到的信息传递给controller
        for (int i = 0; i < teachers.length; i++) {
            if(teachers[i] != null){
                flag = true;
            }
        }
        if(flag){
            return teachers;
        }
        return null;
    }

    public boolean deleteTeacher(String tId) {
        //对数组进行id校验，id存在才让其删除
        int index = isExists(tId);
        //查询出所有数据
        Teacher[] teachers = teacherDao.findAllTeacher();
        if(teachers!=null){
            for (int i = 0; i < teachers.length; i++) {
                if(index!=-1){
                    teacherDao.deleteTeacher(index);
                    return true;
                }
            }
        }
        return false;
    }

    public Teacher selectTeacherById(String tId) {
        int index = isExists(tId);
        Teacher[] teachers = teacherDao.findAllTeacher();
        return teacherDao.selectTeacherByIndex(index);
    }

    /*
    service层修改学生
     */
    public void updateTeacher(String tId, Teacher teacher) {
        teacherDao.updateTeacher(tId,teacher);
    }
}
